const express = require('express')
const sys_user = require('../../../models/sys_user')
const router = express.Router()

const sys_user_role = require('../../../models/sys_user_role')

router.post('/sys/user/update', async (req, res) => {
    try {
        const { email, name, role, password } = req.body

        await sys_user.updatePassword(name, password)

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error(error);
        return res.json({
            "msg": "操作失败！",
            "code": 1,
            "data": null
        })
    }
})


router.post('/sys/user/state', async (req, res) => {
    try {
        const { ids, state } = req.body

        for (const id of ids) {
            await sys_user.updateUserDataFlag(id, state)
        }

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error(error);
        return res.json({
            "msg": "操作失败！",
            "code": 1,
            "data": null
        })
    }
})


router.post('/sys/user/save', async (req, res) => {
    try {
        const {
            id, userName, roles, salt, roleIds, realName,
            password, last_active_time, departId, dataFlag
        } = req.body

        // 检查用户是否存在
        const existingUser = await sys_user.findUserById(id)

        // 构建更新数据对象
        const updateData = {}

        // 设置可更新字段
        if (userName !== undefined) {
            // 检查用户名是否已存在（排除当前用户）
            if (userName !== existingUser.user_name) {
                const userWithSameName = await sys_user.findUserByUsername(userName);
                if (userWithSameName && userWithSameName.id !== id) {
                    return res.json({
                        msg: "用户名已存在",
                        code: 400,
                        success: false
                    })
                }
            }
            updateData.user_name = userName
        }

        if (realName !== undefined) {
            updateData.real_name = realName
        }

        if (roles !== undefined) {
            updateData.role_ids = roles.join(',')

            //删除关联，在插入
            await sys_user_role.deleteUserRoleByUserID(id)

            //向sys_user_role表更新角色
            for (const role of roles) {
                await sys_user_role.addUserRole(id, role)
            }
        }

        if (departId !== undefined) {
            updateData.depart_id = departId;
        }

        if (dataFlag !== undefined) {
            updateData.data_flag = dataFlag;
        }

        if (last_active_time !== undefined) {
            updateData.last_active_time = last_active_time;
        }

        // 处理密码更新（如果有新密码）
        if (password && password.trim()) {
            await sys_user.updatePassword(existingUser.user_name, password)
        }

        // 更新用户基本信息
        await sys_user.updateUser(id, updateData)

        return res.json({ "msg": "请求成功！", "code": 0, "success": true });
    } catch (error) {
        console.error('用户信息更新失败:', error);
        return res.status(500).json({
            msg: "服务器内部错误",
            code: 500,
            success: false
        });
    }
});


router.post('/sys/user/delete', async (req, res) => {
    try {
        const { ids } = req.body

        for (const id of ids) {
            await sys_user.deleteUserById(id)
        }

        return res.json({
            "msg": "请求成功！",
            "code": 0,
            "success": true
        })
    } catch (error) {
        console.error(error);
        return res.json({
            "msg": "操作失败！",
            "code": 1,
            "data": null
        })
    }
})







module.exports = router